import type { WebResult } from "./request";
import { getJSON, postJSON, putJSON, deleteJSON } from './request';


export enum ArticleContentDataType {
  Unknown = "unknown",
  HTML = "html",
  JSON = "json",
  Markdown = "markdown",
}

export enum ArticleContentDataVersion {
  V1 = "v1",
  V2 = "v2",
}

export interface ArticleContentNodeV1 {
  type: string;
  value: string | ArticleContentNodeV1[] | { [key: string]: string };
  alt?: string;
}
export interface ArticleContentNode {
  // 兼容
  type: string;
  value?: string | ArticleContentNodeV1[] | { [key: string]: string };

  tagName: string | "#text";
  textContent?: string; // 文本内容
  // a 标签属性
  href?: string; // 链接的href
  // 图片属性
  src?: string; // 图片的src
  alt?: string; // 图片的alt

  children?: ArticleContentNode[];
}

export interface ArticleContentData {
  type: ArticleContentDataType;
  version?: ArticleContentDataVersion;
  content?: ArticleContentNode[] | string;
}

export interface Article {
  id: number;
  sort_id: number;
  publisher_id: number;
  author?: string;
  author_home_page?: string;
  cover?: string;
  title: string;
  date: string | number | Date;
  content?: string;
  contentData?: ArticleContentData;
  publish_time: string | number | Date;
  update_time: string | number | Date;
  sort: string;
  user: {
    nickname: string;
  };
}

export type ArticleCreateDTO = Omit<
  Article,
  "id" |
  "publisher_id" |
  "textContent" |
  "publish_time" |
  "update_time" |
  "sort" |
  "user"
  > & {
    content_type: "markdown" | "MARKDOWN"
  }
type ArticleUpdateDTO = Partial<Omit<ArticleCreateDTO, "content">> & { content: string; }
const articleAPI = {
  getArticleCount() {
    return getJSON("/api/article/count");
  },

  getArticleViewCount() {
    return getJSON("/api/admin/article/view/count");
  },

  // 获取所有分类
  getArticleAllSort() {
    return getJSON("/api/article/sort/all");
  },

  // 获取文章分页列表
  getArticlePage(page: number, pageSize: number, richContent: boolean = false): Promise<WebResult> {
    return getJSON(`/api/article/page/${page}?pageSize=${pageSize}&richContent=${richContent}`);
  },

  // 创建文章
  createArticle(article: ArticleCreateDTO): Promise<WebResult> {
    return postJSON('/api/article', {
      body: JSON.stringify(article)
    });
  },

  // 更新文章
  updateArticle(id: number, article: ArticleUpdateDTO): Promise<WebResult> {
    return putJSON(`/api/admin/article/${id}`, {
      body: JSON.stringify(article)
    });
  },

  // 删除文章
  deleteArticle(id: number): Promise<WebResult> {
    return deleteJSON(`/api/admin/article/${id}`);
  },
}
export default articleAPI;

